<?php
/**
 * 时间，次数动作捕获 使用之前请初始化$username
 * @author yangzhiguo 2010-09-17
 * @modified by yangzhiguo 2011-03-08
 */
defined('IN_LK') or die('Access Denied');
lk::lo('model', '', 0);
class times_model extends model
{
	private $username;
	private $ip;
	private $starttime;
	private $times;
	
	public function __construct()
	{
		$this->tablename = 'times';
		parent::__construct();
	}
	
	/**
	 * 初始化时间设置
	 */
	public function time_set($username, $expire = LOCKTIME, $times = MAXLOGINTIMES)
	{
		$this->username  = $username;
		$this->ip        = get_ip();
		$this->starttime = TIME - $expire;
		$this->times     = $times;
	}
	
	/**
	 * 取得记录
	 */
	public function time_get()
	{
		return $this->get_one('*', "`username`='$this->username' AND `ip`='$this->ip'");
	}
	
	/**
	 * 增加记录
	 */
	public function add()
	{
		$res = $this->get_one('*', "`username`='$this->username' AND `ip`='$this->ip'");
		if($res)
		{
			$times = $res['time'] <$this->starttime ? 1 : "+=1";
			$this->update(array('times'=>$times), "`username`='$this->username' AND `ip`='$this->ip'");
		}
		else
		{
			$this->insert(array('times'=>1, 'time'=>TIME, 'username'=>$this->username, 'ip'=>$this->ip));
		}
	}
	
	/**
	 * 检查失效
	 * @return boolean 超过系统规定次数返回true, 不超过次数返回false
	 */
	public function denied()
	{
		return (boolean)$this->get_one('*', "`username`='$this->username' AND `ip`='$this->ip' AND `times`>='$this->times' AND `time`>='$this->starttime'");
	}
	
	/**
	 * 清除过期及失效记录
	 */
	public function clear()
	{
		return $this->delete("`username`='$this->username' AND (`ip`='$this->ip' OR `time`<'$this->starttime')");
	}
}